package com.mlethe.library.camera;

import android.media.Image;
import android.media.ImageReader;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.RequiresApi;

/**
 * @author: Mlethe
 * @date: 2021/9/26
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public class ImageAvailableListener implements ImageReader.OnImageAvailableListener {

    /**
     * 预览图像处理
     */
    private Handler mPreviewHandler;

    /**
     * The what field of the message to be sent
     */
    private int mPreviewMessage;

    public void setHandler(Handler previewHandler, int previewMessage) {
        this.mPreviewHandler = previewHandler;
        this.mPreviewMessage = previewMessage;
    }

    @Override
    public void onImageAvailable(ImageReader reader) {
        try {
            if (mPreviewHandler != null) {
                ImageBytes imageBytes = YuvUtil.getBytesFromImageReader(reader);
                if (imageBytes != null) {
                    Message message = mPreviewHandler.obtainMessage(mPreviewMessage, imageBytes.width,
                            imageBytes.height, imageBytes.bytes);
                    message.sendToTarget();
                    mPreviewHandler = null;
                }
            } else {
                Image image = reader.acquireNextImage();
                image.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
